package com.adui.mgt.performance.api;

import cn.hutool.core.collection.CollUtil;
import com.adui.mgt.performance.common.Result;
import com.adui.mgt.performance.entity.Course;
import com.adui.mgt.performance.entity.Performence;
import com.adui.mgt.performance.entity.SubjectCourse;
import com.adui.mgt.performance.entity.User;
import com.adui.mgt.performance.service.CourseService;
import com.adui.mgt.performance.service.PerformenceService;
import com.adui.mgt.performance.service.UserService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 老师录分，学生查分
 **/
@RestController
@RequestMapping("/api/performence")
public class PerformenceApi {

    @Autowired
    private PerformenceService performenceService;

    @Autowired
    private UserService userService;

    @Autowired
    private CourseService courseService;

    /**
     * 给老师用，找人
     * @param depId
     * @param subjectId
     * @return
     */
    @GetMapping("/members/students")
    public Result findPerformenceMembers(@RequestParam("depId") String depId, @RequestParam("subjectId") String subjectId) {
        List<User> users = userService.list(Wrappers.<User>lambdaQuery().eq(User::getDepId, depId).eq(User::getSubjectId, subjectId));
        return Result.data(users);
    }

    /**
     * 通用，用人找课程，找分数
     * @param semester
     * @param userId
     * @return
     */
    @GetMapping("/students/courses")
    public Result findCousesByStudent(@RequestParam("semester") String semester, @RequestParam("userId") String userId) {

        List<Performence> performences = performenceService.list(Wrappers.<Performence>lambdaQuery().eq(Performence::getUserId, userId).eq(Performence::getSemester, semester));
        Set<String> courseIds = performences.stream().map(Performence::getCourseId).collect(Collectors.toSet());
        List<Course> courses = courseService.listByIds(courseIds);
        Map<String, Course> courseMap = courses.stream().collect(Collectors.toMap(Course::getId, Function.identity()));
        for (Performence s : performences) {
            Course course = courseMap.get(s.getCourseId());
            if (Objects.isNull(course)) {
                continue;
            }
            s.setCourseName(course.getCourseName());
            s.setCourseCode(course.getCourseCode());
        }
        return Result.data(performences);
    }

    /**
     * 设置课程或者分数
     * @param performences
     * @return
     */
    @PostMapping("/score")
    public Result setScore(@RequestBody List<Performence> performences) {

        performenceService.saveOrUpdateBatch(performences);
        return Result.ok();
    }

}
